package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.HasStudentException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        List<Clazz> list = clazzMapper.list(clazzQueryParam);
        for (Clazz clazz : list) {
            LocalDate endDate = clazz.getEndDate();
            LocalDate beginDate = clazz.getBeginDate();
            if(LocalDate.now().isBefore(beginDate)){
                clazz.setStatus("未开班");
            }else if(LocalDate.now().isAfter(endDate)){
                clazz.setStatus("已结课");
            }else {
                clazz.setStatus("在读中");
            }
        }
        Page<Clazz> page = (Page<Clazz>) list;
        return new PageResult<>(page.getTotal(),page.getResult());
    }

    @Override
    public void add(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.add(clazz);
    }

    @Override
    public Clazz getInfo(Integer id) {
        return clazzMapper.getInfo(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public void deleteById(Integer id) throws HasStudentException {
        int num = clazzMapper.getStudentCount(id);
        if(num>0){
            throw new HasStudentException("对不起，该班级下有学生，不能直接删除");
        }
        clazzMapper.deleteById(id);
    }

    @Override
    public List<Clazz> selectAll() {
        return clazzMapper.selectAll();
    }
}
